package com.example.sicnuaccountingapp.ui.category

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.sicnuaccountingapp.R
import com.example.sicnuaccountingapp.data.entity.Category
import com.example.sicnuaccountingapp.data.entity.TransactionType
import com.example.sicnuaccountingapp.databinding.FragmentCategoryManagementBinding
import com.example.sicnuaccountingapp.utils.ItemTouchHelperCallback
import com.example.sicnuaccountingapp.utils.PreferencesManager
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.google.android.material.tabs.TabLayout
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
import javax.inject.Inject

@AndroidEntryPoint
class CategoryManagementFragment : Fragment() {
    private var _binding: FragmentCategoryManagementBinding? = null
    private val binding get() = _binding!!

    private val viewModel: CategoryManagementViewModel by viewModels()
    private lateinit var categoryAdapter: CategoryAdapter

    @Inject
    lateinit var preferencesManager: PreferencesManager

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentCategoryManagementBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        setupViews()
        observeState()
        
        viewModel.setUserId(preferencesManager.userId)
    }

    private fun setupViews() {
        setupRecyclerView()
        setupTabLayout()
        setupToolbar()

        binding.addCategoryFab.setOnClickListener {
            showAddCategoryDialog()
        }
    }

    private fun setupRecyclerView() {
        categoryAdapter = CategoryAdapter(
            onEditClick = { category ->
                showEditCategoryDialog(category)
            },
            onDeleteClick = { category ->
                showDeleteConfirmDialog(category)
            },
            onItemMoved = { categories ->
                viewModel.updateCategoryOrder(categories)
            }
        )

        val itemTouchHelper = ItemTouchHelper(
            ItemTouchHelperCallback { fromPosition, toPosition ->
                categoryAdapter.onItemMove(fromPosition, toPosition)
            }
        )

        binding.categoryList.apply {
            adapter = categoryAdapter
            layoutManager = LinearLayoutManager(context)
            itemTouchHelper.attachToRecyclerView(this)
        }
    }

    private fun setupTabLayout() {
        binding.tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab?) {
                val type = when (tab?.position) {
                    1 -> TransactionType.INCOME
                    else -> TransactionType.EXPENSE
                }
                viewModel.setType(type)
            }
            override fun onTabUnselected(tab: TabLayout.Tab?) {}
            override fun onTabReselected(tab: TabLayout.Tab?) {}
        })
    }

    private fun setupToolbar() {
        binding.toolbar.setNavigationOnClickListener {
            findNavController().navigateUp()
        }
    }

    private fun observeState() {
        viewLifecycleOwner.lifecycleScope.launch {
            viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
                viewModel.state.collect { state ->
                    when (state) {
                        is CategoryManagementUiState.Success -> {
                            categoryAdapter.submitList(state.categories)
                        }
                        is CategoryManagementUiState.Error -> {
                            Toast.makeText(context, state.message, Toast.LENGTH_SHORT).show()
                        }
                        CategoryManagementUiState.Loading -> {
                            // 可以显示加载状态
                        }
                    }
                }
            }
        }
    }

    private fun showAddCategoryDialog() {
        EditCategoryDialog.newInstance(
            onSaveClick = { name, iconResourceId ->
                viewModel.addCategory(name, iconResourceId)
            }
        ).show(childFragmentManager, EditCategoryDialog.TAG)
    }

    private fun showEditCategoryDialog(category: Category) {
        EditCategoryDialog.newInstance(
            category = category,
            onSaveClick = { name, iconResourceId ->
                viewModel.updateCategory(category.copy(
                    name = name,
                    iconResourceId = iconResourceId
                ))
            }
        ).show(childFragmentManager, EditCategoryDialog.TAG)
    }

    private fun showDeleteConfirmDialog(category: Category) {
        MaterialAlertDialogBuilder(requireContext())
            .setTitle(R.string.delete_category)
            .setMessage(R.string.delete_category_confirm)
            .setPositiveButton(R.string.confirm) { _, _ ->
                viewModel.deleteCategory(category)
            }
            .setNegativeButton(R.string.cancel, null)
            .show()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
} 